package com.example.springboot.controller.api;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.springboot.common.Constants;
import com.example.springboot.common.Result;
import com.example.springboot.common.RoleEnum;
import com.example.springboot.controller.dto.PersonalDTO;
import com.example.springboot.controller.dto.UserDTO;
import com.example.springboot.controller.dto.UserPasswordDTO;
import com.example.springboot.entity.Articles;
import com.example.springboot.entity.Follows;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.ArticlesMapper;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.service.IArticlesService;
import com.example.springboot.service.IFollowsService;
import com.example.springboot.service.IUserService;
import com.example.springboot.service.impl.UserServiceImpl;
import com.example.springboot.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
/**
 * <p>
 * 登录注册用户表 API控制器 - 不需要token验证的API
 * </p>
 *
 * @author
 */
@RestController
@RequestMapping("api/user")
public class UserApi {
    @Resource
    private IUserService iUserService;



    @Resource
    private IFollowsService iFollowsService;

    @Resource
    private IArticlesService iArticlesService;

    @Resource
    private ArticlesMapper articlesMapper;

    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        UserDTO dto = iUserService.login(userDTO);
        return Result.success(dto);
    }



    // 新增或者更新
    @PostMapping("/register")
    public Result save(@RequestBody User user) {
        String username = user.getUsername();
        if (StrUtil.isBlank(username)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        if (StrUtil.isBlank(user.getNickname())) {
            user.setNickname(username);
        }
        User one = iUserService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
        if (one == null) {
            if (user.getId() != null) {
                user.setPassword(null);
            } else {
                if (user.getPassword() == null) {
                    user.setPassword("123");
                }
            }
            user.setRole(RoleEnum.ROLE_USER.toString());
//            save(user);  // 把 copy完之后的用户对象存储到数据库
            return Result.success(iUserService.saveOrUpdate(user));
        }else {
            throw new ServiceException(Constants.CODE_600, "用户已存在");
        }

    }

    /**
     * 修改密码
     *
     * @param userPasswordDTO
     * @return
     */
    @PostMapping("/password")
    public Result password(@RequestBody UserPasswordDTO userPasswordDTO) {
        iUserService.updatePassword(userPasswordDTO);
        return Result.success();
    }


    @GetMapping("/info/{username}")
    public Result findByUsername(@PathVariable String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return Result.success(iUserService.getOne(queryWrapper));
    }

    @PostMapping("/update")
    public Result updateByUsername(@RequestBody User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        return Result.success(iUserService.update(user,queryWrapper));
    }


    //个人主页信息
    @GetMapping("/personal/{id}")
    public Result findByPersonal (@PathVariable Integer id) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        QueryWrapper<Follows> followsQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Follows> likesQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Articles> articlesQueryWrapper = new QueryWrapper<>();
        followsQueryWrapper.eq("follower_id",id);
        likesQueryWrapper.eq("following_id",id);
        articlesQueryWrapper.eq("author_id",id);
        Integer followNum = (int) iFollowsService.count(followsQueryWrapper);
        Integer likesNum = (int) iFollowsService.count(likesQueryWrapper);
        Integer articlesNum =(int) iArticlesService.count(articlesQueryWrapper);
        User one = iUserService.getOne(queryWrapper);
        System.out.println("名称"+one.getNickname());
        PersonalDTO personalDTO=new PersonalDTO();
        personalDTO.setId(one.getId());
        personalDTO.setUsername(one.getUsername());
        personalDTO.setNickName(one.getNickname());
        personalDTO.setAvatar(one.getAvatarUrl());
        personalDTO.setFollowNum(followNum);
        personalDTO.setLikesNum(likesNum);
        personalDTO.setArticlesNum(articlesNum);
        return Result.success(personalDTO);
    }
}
